package net.zjitc.utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet(name = "DispacherServlet",urlPatterns = "/")
public class DispacherServlet extends HttpServlet {
    Map<String,Method> urlMap = new HashMap<>();
    Map<Method,Class> methodMap= new HashMap<>();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //请求的url是什么？？
        String servletPath = req.getServletPath();
        //从urlmap中找是否有此url,如果没有怎么办？404
        if (!urlMap.containsKey(servletPath)){
            resp.setStatus(404);
            return;
        }
        //有此url,method class
        Method method = urlMap.get(servletPath);
        Class clazz = methodMap.get(method);
        //生成obj对象
        try {
            Object object = clazz.newInstance();
            //调用方法，返回值
            String str = (String) method.invoke(object,req,resp);
            if (str!=null ||"".equals(str)){
                if (str.startsWith("Redirect:")){
                    //重定向
                    resp.sendRedirect(str.substring(9));
                }else {
                    //请求转发
                    req.getRequestDispatcher(str).forward(req,resp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        //找包下的所有的class
        List<Class> list = getControllerClass("net.zjitc.controller");
        //通过遍历class 将url  mehtod  class放入集合中
        for (Class c: list){
            Method[] methods = c.getMethods();
            for (Method m:methods){
                URLMapping annotation = m.getAnnotation(URLMapping.class);
                if (annotation!= null){
                    String url = annotation.url();
                    urlMap.put(url,m);
                    methodMap.put(m,c);
                }
            }
        }
    }

    private List<Class> getControllerClass(String pageName) {
       // String pageName = "net.zjitc.controller";
        URL resource = Thread.currentThread().getContextClassLoader().getResource(pageName.replace(".", "/"));
        String dir = resource.getPath();
        //根据此路径，创建文件对象
        File file = new File(dir);
        //如果文件对象是一个文件夹的话，通过list()方法找到所有的文件名
        if (file.isDirectory()){
            String[] list = file.list();
            List<String> nameList = new ArrayList<>();
            //对文件名进行处理，生成完成的类的名称（包名+类名，不带后缀）
            for(String name:list){
                nameList.add(pageName+"."+name.substring(0,name.length()-6));
            }
            //根据包名，生成Class 类对象
            List<Class> classList = new ArrayList<>();
            for (String s:nameList){
                try {
                    classList.add(Class.forName(s));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            return classList;
        }
        return null;
    }

}
